package top.jnaw.test.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import top.jnaw.test.model.Dept;

/**
 * Permissions 管理
 * 描述：
 */
public class DeptService {

	//private static final Log log = Log.getLog(PermissionsService.class);
  public static final Dept dao = new Dept().dao();

  /**
   * 获取所有的部门列表（）
   */
  public static List<Dept> getList() {
    String sql = "SELECT * FROM dept ";
    return dao.find(sql);
  }

  /**
   * 这个是获取某个组织下的得所有子部门，并且将每个子部门的人数查出来(没算)，但是没有总人数（重要）
   */
  public static JSONArray getChildren(List<Dept> list, int parent,
      JSONArray tail) {
    if (null == tail) {
      tail = new JSONArray();
    }
    for (Dept d : list) {
      if (d.getFid().intValue() == parent) {
        JSONObject child = new JSONObject();
        child.put("id", d.getId());
        child.put("name", d.getName());
        child.put("fid", d.getFid());
        //这个是每个部门的单独人数
//        if (dao.find("select * from users where depid=?", d.getId())
//            != null) {
//          child.put("num",
//              dao.find("select * from users where depid=?", d.getId())
//                  .size());
//        } else {
//          child.put("num", 0);
//        }
        JSONArray grandChildren = getChildren(list, d.getId(), null);
        if (!grandChildren.isEmpty()) {
          child.put("children", grandChildren);
        }
        tail.add(child);
      }
    }
    return tail;
  }

  /**
   * 获取部门编号下所有的人，包括子级部门的人
   *
   * @param DeptIds 123,222,3333
   */
  public static Page<Record> getUserString(String DeptIds, String name, int userstate, int page,
      int size) {
    Page<Record> UsersList = null;
    //获取单位id的子级单位id
    String depidString2 = getdeptsString(DeptIds);
    if (StrKit.notBlank(depidString2)) {
      //获取所有单位id内的所有人员
      UsersList = getDeparmentPeople(depidString2, name, userstate, page, size);
    }
    return UsersList;
  }


  /**
   * 第一步，获取DeptIds 下的所有子级id的字符串，包括自己，调用getDeptIds来获取子级id
   *
   * @param DeptIds 1,2,3,4
   */
  public static String getdeptsString(String DeptIds) {
    Page<Record> UsersList = null;
    //获取单位id的子级单位id
    if (StrKit.notBlank(DeptIds)) {
      String[] depids = DeptIds.split(",");
//      int[] DeptIdArr = new int[depids.length];//存储前台传过来的部门id
      List<Dept> DeptList = getList();
      //将DeptIds中的id的子级id也查出来
      Map<String, String> DeptMap = new HashMap<>();
      for (int i = 0; i < depids.length; i++) {
        int fid = Integer.parseInt(depids[i]);
        DeptMap.put(depids[i],depids[i]);
        DeptMap.putAll(getDeptIds2(DeptList, fid, DeptMap));
      }
      //将map型的id转换成规定格式的1,2,3,4
      StringBuilder depidString = new StringBuilder();
      for (String key : DeptMap.keySet()) {
        depidString.append(key + ",");
      }

      if (StrKit.notBlank(depidString.toString())) {
        String depidString2 = depidString.substring(0, depidString.length() - 1);
        return depidString2;
      }

    }
    return null;
  }



  public static Map getDeptIds2(List<Dept> list, int parent,
      Map<String, String> DeptMap) {
    if (null == DeptMap) {
      DeptMap = new HashMap<>();
    }
    for (Dept d : list) {
      if (d.getFid().intValue() == parent) {
        DeptMap.put(d.getId() + "", d.getId() + "");
        getDeptIds2(list, d.getId(), DeptMap);
      }
    }
    return DeptMap;
  }

  /**
   * 根据多个部门id查询员工信息（重要）
   */
  public static Page<Record> getDeparmentPeople(String DeptIds, String name, int userstate,
      int page, int size) {

    Page<Record> userList = null;
    String select = " SELECT"
        + " u.id,"
        + " u.name,"
        + " ud.id AS user_deptid,"
        + " d.name AS dept_name";
    String except = " FROM users u LEFT JOIN user_dept ud ON u.id = ud.user_id"
        + "  LEFT JOIN dept d ON ud.dept_id = d.id "
        + " WHERE d.id IN ('" + DeptIds + "')"
        + " and 1 = ? ";

    List<Object> para = new ArrayList<>();
    para.add(1);
    if (StrKit.notBlank(name)) {
      except += " and u.name like ? ";
      para.add("%" + name + "%");
    }
//    if (StrKit.notBlank(phone)) {
//      except += " and u.phone like ? ";
//      para.add("%" + phone + "%");
//    }
//    if (rolename.equals("-1")) {
//      except += " and u.username not in ( SELECT username FROM user_roles GROUP BY username) ";
//    } else if (StrKit.notBlank(rolename)) {
//      except += " and ur.role_name = ? ";
//      para.add(rolename);
//    }
    //用户的删除状态
//    if (userstate == 0) {
//      except += " and u.state = ? ";
//      para.add(0);
//    } else {
//      except += " and u.state = ? ";
//      para.add(1);
//    }
    except += " order by u.id ";
    Object[] objects = para.toArray();

    userList = Db.paginate(page, size, select, except, objects);//部门id为ids时的所有员工信息

    return userList;
  }

}